package com.efast.dmom.mgmt.service.mes.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.efast.cafe.framework.bean.ResultBean;
import com.efast.cafe.framework.exception.ServiceException;
import com.efast.cafe.framework.util.SpringWebUtils;
import com.efast.cafe.portal.entity.base.PortalBaseLov;
import com.efast.cafe.portal.remote.base.PortalBaseLovService;
import com.efast.cafe.util.date.DateUtils;
import com.efast.dmom.mgmt.dao.mes.PrBasPrintVinLabelDao;
import com.efast.dmom.mgmt.entity.mes.PrBasPrintVinLabel;
import com.efast.dmom.mgmt.service.mes.PrBasPrintVinLabelService;

@Service
public class PrBasPrintVinLabelServiceImpl implements PrBasPrintVinLabelService {

	@Autowired
	PrBasPrintVinLabelDao prBasPrintVinLabelDao;

	@Autowired
	private PortalBaseLovService pbsi;

	@Override
	public void savePrintInfo(PrBasPrintVinLabel enti) {
		// TODO Auto-generated method stub
		prBasPrintVinLabelDao.savePrintInfo(enti);
	}

	// 生产vin标签模板，带车型和颜色
	@Override
	public File getVinLabelPrintInfo(String vin, String model, String vehicleColor) {
		String data = DateUtils.getCurrentTimeNumber();
		// TODO Auto-generated method stub
		File fileName = new File("C:\\temp\\zebra\\" + vin + "vinPrint" + data + ".zpl");
		// 如果路径文件夹不存在则创建新的文件夹
		// fileParent = fileName.getParentFile();
		File fileParent = fileName.getParentFile();

		if (!fileParent.exists()) {
			fileParent.mkdirs();
		}

		try {
			fileName.createNewFile();
			FileOutputStream outStream = new FileOutputStream(fileName);
			OutputStreamWriter out = new OutputStreamWriter(outStream, "UTF-8");
			out.write("^XA");
			out.write("^MMT");
			out.write("^PW1004");
			out.write("^LL0236");
			out.write("^LS0");
			// out.write("^BY3,3,145^FT39,165^BCN,,N,N")
			out.write("^BY4,3,157^FT40,196^BCN,,N,N");
			out.write("^FD" + vin + "^FS");
			// 设置字体
			out.write("^CW1,E:MSUNG.FNT^FS");
			out.write("^SEE:GB18030.DAT");
			// 设置编码
			out.write("^CI28");
			out.write("^FT940,73^A1N,35,20^FD" + model + "^FS");
			out.write("^FT940,166^A1N,42,25^FD" + vehicleColor + "^FS");
			out.write("^FT365,230^A0N,37,36^FB334,1,0,^FD" + vin + "^FS");
			out.write("^PQ1,0,1,Y^XZ");
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return fileName;
	}

	// 打印vin标签，带车型和颜色
	@Override
	public void printVinLabel(String vin, String model, String vehicleColor, String printFunction,
			Boolean printStatus) {

		// 获取打印机名称
		List<PortalBaseLov> list = pbsi.api_queryListByParamKey1(printFunction);
		if (list == null || list.size() < 1) {
			throw new ServiceException("无法获取打印机名称");
		}
		String printName = list.get(0).getOption_key();
		// 保存打印记录
		PrBasPrintVinLabel prBasPrintVinLabel = new PrBasPrintVinLabel();
		prBasPrintVinLabel.setVin(vin);
		prBasPrintVinLabel.setPrint_value1(model);
		prBasPrintVinLabel.setPrint_value2(vehicleColor);
		prBasPrintVinLabel.setPrint_function(printFunction);
		prBasPrintVinLabel.setCompanyCode(SpringWebUtils.getRequestCompany());
		if (printStatus) {
			prBasPrintVinLabel.setPrint_status("已打印");
		} else {
			prBasPrintVinLabel.setPrint_status("已重打");
		}

		prBasPrintVinLabel.setPrint_time(DateUtils.getCurrentDate());
		prBasPrintVinLabel.setPrint_user(SpringWebUtils.getRequestUser());
		prBasPrintVinLabelDao.savePrintInfo(prBasPrintVinLabel);

		// TODO Auto-generated method stub
		File fileName = getVinLabelPrintInfo(vin, model, vehicleColor);
		// 根据打印功能（printFunction）或者配置的打印机名称

		HashPrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
		DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
		// 查找所有的可用的打印服务
		PrintService[] printService = PrintServiceLookup.lookupPrintServices(flavor, pras);
		Boolean isPrint = false;
		for (PrintService printer : printService) {
			if (printer.getName().equals(printName)) {
				DocPrintJob job = printer.createPrintJob();
				try {
					FileInputStream in = new FileInputStream(fileName);
					SimpleDoc doc = new SimpleDoc(in, flavor, null);
					try {
						job.print(doc, null);
						isPrint = true;
					} catch (PrintException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}
		if (!isPrint) {
			throw new ServiceException("无法匹配到本机打印机！");
		}

	}

	// 生产vin标签模板指令
	@Override
	public File getVinLabelPrintInfo(String vin) {

		// TODO Auto-generated method stub
		String data = DateUtils.getCurrentTimeNumber();
		// TODO Auto-generated method stub
		File fileName = new File("C:\\temp\\zebra\\" + vin + "QualityVIN" + data + ".zpl");
		// 如果路径文件夹不存在则创建新的文件夹
		// fileParent = fileName.getParentFile();
		File fileParent = fileName.getParentFile();

		if (!fileParent.exists()) {
			fileParent.mkdirs();
		}

		try {
			fileName.createNewFile();
			FileOutputStream outStream = new FileOutputStream(fileName);
			OutputStreamWriter out = new OutputStreamWriter(outStream, "UTF-8");
			out.write("^XA");
			out.write("^RS,,,3,N");
			out.write("^RR3");
			out.write("^XZ");
			out.write("^XA");
			out.write("~SD30");
			out.write("^SZ2^JMA");
			out.write("^MCY^PMN");
			out.write("^PW1200");
			out.write("~JSN");
			out.write("^JZY");
			out.write("^LH0,0^LRN");
			out.write("^XZ");
			out.write("^XA");
			out.write("^FO155,20");
			out.write("^BY3.5^BCN,130,N,N^FD" + vin + "^FS");
			out.write("^FT260,210");
			out.write("^CI0");
			out.write("^ADN,50,30^FD" + vin + "^FS");
			out.write("^CW1,E:MSUNG.FNT^FS");
			out.write("^SEE:GB18030.DAT");
			out.write("^FO120,87");
			out.write("^XGR:SSGFX000.GRF,1,1^FS");
			out.write("^PQ1,0,1,Y");
			out.write("^XZ");
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return fileName;
	}

	// 打印vin标签，只有一个vin号的标签
	@Override
	public ResultBean printVinLabel(PrBasPrintVinLabel enti) {
		// TODO Auto-generated method stub
		ResultBean result = new ResultBean(true, "'");
		result.setSuccess(true);
		// 获取打印机名称
		String printName = enti.getPrintName();
		String vin = enti.getVin();
		String printType = enti.getPrintType();
		boolean printStatus = enti.isPrintStatus();
		String templateName = enti.getTemplateName();
		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("vin", vin);
		parameters.put("printType", printType);
		parameters.put("printUser", SpringWebUtils.getRequestUser());
		parameters.put("printStatus", printStatus);
		parameters.put("printName", printName);
		parameters.put("templateName", templateName);
		// 将map转成json格式
		String jsonString = JSONObject.toJSONString(parameters);
		// 获取配置的打印服务的URL
		List<PortalBaseLov> lists = pbsi.api_queryListByParamKey1("PrintUrl");
		if (lists == null || lists.size() < 1) {
			result.setSuccess(false);
			result.setMessage("无法获取打印服务的URL");
			return result;
		}
		String printUrl = lists.get(0).getOption_key();
		// 连接webservice接口进行打印
		JaxWsDynamicClientFactory dcflient = JaxWsDynamicClientFactory.newInstance();

		// 调打印接口
		try {
			// 连接打印服务
			Client client = dcflient.createClient(printUrl);
			Object[] results = client.invoke("zebraPrintVinLabel", jsonString);
			System.out.println(results[0]);
			if (results[0] != null) {
				result.setSuccess(false);
				result.setMessage((String) results[0]);
				return result;
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			result.setSuccess(false);
			result.setMessage("无法连接打印服务器！");
			return result;
		}

		return result;
	}

	@Override
	public File getPartNoPrintInfo(String partNo) {
		// TODO Auto-generated method stub
		String data = DateUtils.getCurrentTimeNumber();
		// TODO Auto-generated method stub
		File fileName = new File("C:\\temp\\zebra\\" + partNo + "partNo" + data + ".zpl");
		// 如果路径文件夹不存在则创建新的文件夹
		// fileParent = fileName.getParentFile();
		File fileParent = fileName.getParentFile();

		if (!fileParent.exists()) {
			fileParent.mkdirs();
		}

		try {
			fileName.createNewFile();
			FileOutputStream outStream = new FileOutputStream(fileName);
			OutputStreamWriter out = new OutputStreamWriter(outStream, "UTF-8");
			out.write("^XA");
			out.write("^MMT");
			out.write("^PW827");
			out.write("^LL0236");
			out.write("^LS0");
			out.write("^BY4,3,116^FT59,162^BCN,,Y,N");
			out.write("^FD00045678901234567890123456^FS");
			out.write("^PQ1,0,1,Y");
			out.write("^XZ");
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return fileName;
	}

	@Override
	public ResultBean printPartNoLabel(PrBasPrintVinLabel enti) {
		// TODO Auto-generated method stub
		ResultBean result = new ResultBean(true, "'");
		result.setSuccess(true);
		// 获取打印机名称
		String printName = enti.getPrintName();
		String partNo = enti.getVin();
		String templateName = enti.getTemplateName();
		String printType = enti.getPrintType();
		Boolean printStatus= enti.isPrintStatus();
		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("partNo", partNo);
		parameters.put("printType", printType);
		parameters.put("printUser", SpringWebUtils.getRequestUser());
		parameters.put("printStatus", printStatus);
		parameters.put("printName", printName);
		parameters.put("templateName", templateName);
		// 将map转成json格式
		String jsonString = JSONObject.toJSONString(parameters);
		// 获取配置的打印服务的URL
		List<PortalBaseLov> lists = pbsi.api_queryListByParamKey1("PrintUrl");
		if (lists == null || lists.size() < 1) {
			result.setSuccess(false);
			result.setMessage("无法获取打印服务的URL");
			return result;
		}
		String printUrl = lists.get(0).getOption_key();
		// 连接webservice接口进行打印
		JaxWsDynamicClientFactory dcflient = JaxWsDynamicClientFactory.newInstance();

		// 调打印接口
		try {
			// 连接打印服务
			Client client = dcflient.createClient(printUrl);
			Object[] results = client.invoke("zebraPrintPartNo", jsonString);
			System.out.println(results[0]);
			if (results[0] != null) {
				result.setSuccess(false);
				result.setMessage((String) results[0]);
				return result;
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			result.setSuccess(false);
			result.setMessage("无法连接打印服务器！");
			return result;
		}

		return result;

	}

	// 序列打印零部件条码
	@Override
	public ResultBean printPartNoLabelList(PrBasPrintVinLabel enti) {
		ResultBean result = new ResultBean(true, "'");
		// TODO Auto-generated method stub
		// 获取打印机名称
//		List <PortalBaseLov> list = pbsi.api_queryListByParamKey1(printFunction);
//		if(list==null || list.size()<1) {			
//			throw new ServiceException("无法获取打印机名称");
//		}
//		String printName=list.get(0).getOption_key();
		String printName = enti.getPrintName();
		String partNo = enti.getVin();
		String templateName = enti.getTemplateName();
		String printType = enti.getPrintType();
		Integer beginNo = enti.getBeginNum();
		Integer endNo = enti.getEndNum();

		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("partNo", partNo);
		parameters.put("printType", printType);
		parameters.put("printUser", SpringWebUtils.getRequestUser());
		parameters.put("printName", printName);
		parameters.put("beginNo", beginNo);
		parameters.put("endNo", endNo);
		parameters.put("templateName", templateName);
		// 将map转成json格式
		String jsonString = JSONObject.toJSONString(parameters);

		// 连接webservice接口进行打印
		JaxWsDynamicClientFactory dcflient = JaxWsDynamicClientFactory.newInstance();
		// 获取配置的打印服务的URL
		List<PortalBaseLov> lists = pbsi.api_queryListByParamKey1("PrintUrl");
		if (lists == null || lists.size() < 1) {
			// return "无法获取打印服务的URL";
		}
		String printUrl = lists.get(0).getOption_key();
		// 调打印接口
		try {
			// 连接打印服务
			Client client = dcflient.createClient(printUrl);
			Object[] results = client.invoke("zebraPrintPartNoList", jsonString);
			if (results[0] != null) {
				result.setSuccess(false);
				result.setMessage((String) results[0]);
				return result;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			result.setSuccess(false);
			result.setMessage("无法连接打印服务器");
			return result;
		}

		// }
		return result;

	}

}
